package com.plian.system.service.fr.bulletin.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.read.listener.PageReadListener;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillConfig;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plian.Tools.*;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.bean.fr.NewBulletinExcelBean;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.constant.yth.YthConstant;
import com.plian.system.dao.bt.baseinfo.BaseInfoDao;
import com.plian.system.dao.fr.bulletin.BulletinDao;
import com.plian.system.dao.sys.orgzation.OrgzationDao;
import com.plian.system.entity.fr.bulletin.BulletinValue;
import com.plian.system.entity.fr.bulletin.NewBulletin;
import com.plian.system.entity.sys.Org;
import com.plian.system.excel.ImportExcelUtil;
import com.plian.system.listener.NewBulletinEvent;
import com.plian.system.mapper.fr.bulletin.BulletinMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.fr.bulletin.IBulletinSummaryRelationService;
import com.plian.system.service.fr.bulletin.IBulletinValueService;
import com.plian.system.service.fr.bulletin.INewBulletinService;
import com.plian.system.service.sys.orgzation.IOrgService;
import com.plian.system.service.sys.orgzation.OrgzationService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.service.yth.helper.YthExcelUtils;
import com.plian.system.vo.fr.bulletin.*;
import com.plian.system.vo.yth.YthExcelInfoVO;
import com.plian.system.vo.yth.YthResult;
import com.plian.system.wrapper.fr.bulletin.NewBulletinWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.plian.system.constant.sys.FormStatusConstant.FINISH;
import static com.plian.system.constant.sys.FormTypeConstant.FR_BULLETIN;
import static com.plian.system.constant.sys.TableTypeCode.DIFFERENCE_TABLE_TYPE;
import static com.plian.system.constant.yth.YthConstant.EXCEL_MERGE;
import static com.plian.system.constant.yth.YthConstant.EXCEL_SINGLE;

/**
 * 服务实现类 快报主表
 *
 * @author gangan
 * @since 2021-02-02
 */
@Slf4j
@Service
@AllArgsConstructor
public class NewBulletinServiceImpl extends ServiceImpl<BulletinMapper, NewBulletin> implements INewBulletinService {

    /**
     * logger属性.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(NewBulletinServiceImpl.class);


    private BaseInfoDao baseInfoDao;

    private BulletinDao bulletinDao;

    private IBulletinValueService bulletinValueService;

    private OrgzationDao orgzationDao;

    private OrgzationService orgzationService;

    private FormWorkflowService formWorkflowService;

    private ApplicationContext applicationContext;

    private IBulletinSummaryRelationService bulletinSummaryRelationService;

    private NewBulletinWrapper newBulletinWrapper;

    private IOrgService orgService;

    private static final String NUMBER_DOT_PATTERN = "^\\d{1,2}\\..*?";

    private final List<String> NOT_UPDATE_STATUS = Stream
            .of(FormStatusConstant.FLOW + "", FormStatusConstant.FINISH + "").collect(Collectors.toList());

    @Override
    public List<BulletinValue> getInitByYear(String year, String bulletinId){
        List<BulletinValue> bulletinValues = new ArrayList<>();
        try {
            List<BulletinTypeVO> typeVOS = baseInfoDao.findBulletin(year);
            int index = 1;
            for (BulletinTypeVO typeVO : typeVOS){
                BulletinValue bulletinValue = BulletinValue.builder().columnName(typeVO.getValIndustryCode()).typeCode(typeVO.getCode())
                        .typeName(typeVO.getName()).bulletinId(bulletinId).id(UuidUtil.get32UUID()).sortCode(typeVO.getSortCode()).disabled(false).build();
                if ("3".equals(typeVO.getYesOrNo()) || "4".equals(typeVO.getYesOrNo())){
                    List<BulletinYearNameVO> yearNameVOS = JSON.parseArray(typeVO.getReamark(), BulletinYearNameVO.class);
                    if (CollectionUtil.isNotEmpty(yearNameVOS)){
                        for (BulletinYearNameVO yearNameVO : yearNameVOS){
                            if (year.equals(yearNameVO.getYear())){
                                bulletinValue.setTypeName(yearNameVO.getTypeName());
                            }
                        }
                    }
                }
                if ("1".equals(typeVO.getYesOrNo()) || "4".equals(typeVO.getYesOrNo())){
                    bulletinValue.setTypeName(index + StringPool.DOT + bulletinValue.getTypeName());
                    index += 1;
                }
                if ("1".equals(typeVO.getTsVersion())){
                    bulletinValue.setDisabled(true);
                }
                bulletinValues.add(bulletinValue);
            }
        }catch (Exception e){
            log.error(ExceptionUtils.getFullStackTrace(e));
        }
        return bulletinValues;
    }


    @Override
    public void oldDataToNew() {
        List<NewBulletin> allList = list();
        for (NewBulletin newBulletin : allList){
            PageData pd = new PageData();
            pd.put("id", newBulletin.getId());
            List<BulletinValue> initList = getInitByYear(DateUtil.format(newBulletin.getReportTime(), DateUtil.PATTERN_YEAR), newBulletin.getId());
            try {
                PageData oldData = bulletinDao.findById(pd);
                for (BulletinValue bulletinValue : initList){
                    if (oldData.containsKey(bulletinValue.getColumnName())){
                        bulletinValue.setMonthAmount(BigDecimalUtil.toBigdecimal(oldData.getString(bulletinValue.getColumnName())));
                    }

                    if (oldData.containsKey("SUM_" + bulletinValue.getColumnName())){
                        bulletinValue.setYearAmount(BigDecimalUtil.toBigdecimal(oldData.getString("SUM_" + bulletinValue.getColumnName())));
                    }

                    if (oldData.containsKey("LAST_" + bulletinValue.getColumnName())){
                        bulletinValue.setLastYearMonthAmount(BigDecimalUtil.toBigdecimal(oldData.getString("LAST_" + bulletinValue.getColumnName())));
                    }
                }
                bulletinValueService.saveBatch(initList);
            }catch (Exception e){
                log.error(ExceptionUtils.getFullStackTrace(e));
            }

        }
    }

    @Override
    public R originReport(String reportTime) {
        String orgId = TokenUtil.getTokenOrgId();
        R objResult;
        if (StringUtil.isBlank(orgId)){
            objResult = new R(CommonCode.NORMAL);
            objResult.setMessage("请先选择填报时间");
        }
        try {
            PageData org = orgzationDao.findbyid(orgId);
            List<PageData> parentList = new ArrayList<>();
            orgzationService.getParentList(org.getString("parentId"), parentList);
            int summaryCode = parentList.size();
            int tempCode = summaryCode;
            int isExist = 0;
            String tablename = "";
            String formTypeCode[] = {"0", "1", "6"};
            String formTypeCode2[] = {"1", "6"};
            reportTime = reportTime + "-01";
            String year = reportTime.split(StringPool.DASH)[0];

            NewBulletin report;
            switch (org.getString("typeCode")){
                case "0":
                    for (int i = 0; i < formTypeCode.length; i++){
                        String tableTypeCode = formTypeCode[i];
                        LambdaQueryWrapper<NewBulletin> queryWrapper = new LambdaQueryWrapper<>();
                        queryWrapper.eq(NewBulletin::getReportTime, reportTime);
                        queryWrapper.eq(NewBulletin::getOrgId, orgId);
                        queryWrapper.eq(NewBulletin::getTableTypeCode, tableTypeCode);

                        if ("6".equals(tableTypeCode)) {
                            queryWrapper.eq(NewBulletin::getSummaryCode, summaryCode - 1);
                            tempCode = summaryCode - 1;
                        } else {
                            queryWrapper.eq(NewBulletin::getSummaryCode, summaryCode);
                        }

                        report = getOne(queryWrapper);
                        if (report == null){
                            saveAndChild(year, orgId, tableTypeCode, reportTime, tempCode + "");
                            tempCode = summaryCode;
                        }else {
                            if ("6".equals(tableTypeCode)) {
                                tablename += "“集团合并表”、";
                                isExist = 1;
                            } else if ("1".equals(tableTypeCode)) {
                                tablename += "“差额表”、";
                                isExist = 1;
                            } else {
                                tablename += "“单户表”、";
                                isExist = 1;
                            }
                        }
                    }
                    break;

                case "1":
                    LambdaQueryWrapper<NewBulletin> queryWrapper1 = new LambdaQueryWrapper<>();
                    queryWrapper1.eq(NewBulletin::getReportTime, reportTime);
                    queryWrapper1.eq(NewBulletin::getOrgId, orgId);
                    queryWrapper1.eq(NewBulletin::getTableTypeCode, "0");
                    queryWrapper1.eq(NewBulletin::getSummaryCode, summaryCode - 1);
                    report = getOne(queryWrapper1);
                    if (report == null) {
                        saveAndChild(year, orgId, "0", reportTime, summaryCode - 1 + "");
                    } else {
                        isExist = 1;
                    }
                    break;
                case "2":
                    LambdaQueryWrapper<NewBulletin> queryWrapper2 = new LambdaQueryWrapper<>();
                    queryWrapper2.eq(NewBulletin::getReportTime, reportTime);
                    queryWrapper2.eq(NewBulletin::getOrgId, orgId);
                    queryWrapper2.eq(NewBulletin::getTableTypeCode, "0");
                    queryWrapper2.eq(NewBulletin::getSummaryCode, summaryCode);
                    report = getOne(queryWrapper2);
                    if (report == null) {
                        saveAndChild(year, orgId, "0", reportTime, summaryCode + "");
                    } else {
                        isExist = 1;
                    }
                    break;

                case "3":
                    for (int i = 0; i < formTypeCode.length; i++) {
                        LambdaQueryWrapper<NewBulletin> queryWrapper3 = new LambdaQueryWrapper<>();
                        queryWrapper3.eq(NewBulletin::getReportTime, reportTime);
                        queryWrapper3.eq(NewBulletin::getOrgId, orgId);
                        String tableTypeCode = formTypeCode[i];
                        queryWrapper3.eq(NewBulletin::getTableTypeCode, tableTypeCode);

                        if ("6".equals(tableTypeCode)) {
                            queryWrapper3.eq(NewBulletin::getSummaryCode, summaryCode);
                            tempCode = summaryCode;
                        } else {
                            queryWrapper3.eq(NewBulletin::getSummaryCode, summaryCode + 1);
                            tempCode = summaryCode + 1;
                        }

                        report = getOne(queryWrapper3);
                        if (report == null){
                            saveAndChild(year, orgId, tableTypeCode, reportTime, tempCode + "");
                        }else {
                            if ("6".equals(tableTypeCode)) {
                                tablename += "“集团合并表”、";
                                isExist = 1;
                            } else if ("1".equals(tableTypeCode)) {
                                tablename += "“差额表”、";
                                isExist = 1;
                            } else {
                                tablename += "“单户表”、";
                                isExist = 1;
                            }
                        }
                    }
                    for (int i = 0; i < formTypeCode2.length; i++) {
                        String tableTypeCode = formTypeCode2[i];

                        LambdaQueryWrapper<NewBulletin> queryWrapper4 = new LambdaQueryWrapper<>();
                        queryWrapper4.eq(NewBulletin::getReportTime, reportTime);
                        queryWrapper4.eq(NewBulletin::getOrgId, orgId);
                        queryWrapper4.eq(NewBulletin::getTableTypeCode, tableTypeCode);
                        if ("6".equals(tableTypeCode)) {
                            queryWrapper4.eq(NewBulletin::getSummaryCode, summaryCode - 1);
                            tempCode = summaryCode - 1;
                        } else {
                            queryWrapper4.eq(NewBulletin::getSummaryCode, summaryCode);
                            tempCode = summaryCode;
                        }
                        report = getOne(queryWrapper4);
                        if (report == null) {
                            saveAndChild(year, orgId, tableTypeCode, reportTime, tempCode + "");
                        } else {
                            if ("6".equals(tableTypeCode)) {
                                tablename += "“集团合并表(分公司)” ";
                                isExist = 1;
                            } else if ("1".equals(tableTypeCode)) {
                                tablename += "“差额表(分公司)” ";
                                isExist = 1;
                            } else {
                                tablename += "“单户表” ";
                                isExist = 1;
                            }
                        }
                    }
                    break;
                default:
                    break;
            }

            if (isExist == 0) {
                objResult = new R(CommonCode.SUCCESS);
            } else {
                objResult = new R(CommonCode.NORMAL);
                objResult.setMessage("已存在本年度" + tablename + ",其余表新建成功");
            }

        }catch (Exception e){
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            objResult = new R(CommonCode.ERROR);
            return objResult;
        }

        return objResult;
    }

    @Override
    public R delete(String bulletinId) {
        R objResult;
        NewBulletin newBulletin = getById(bulletinId);
        if (newBulletin == null){
            objResult = new R(CommonCode.ERROR);
            return objResult;
        }
        List<String> ids = new ArrayList<>();
        if ("6".equals(newBulletin.getTableTypeCode())){
            List<NewBulletin> list = list(new LambdaQueryWrapper<NewBulletin>()
                    .eq(NewBulletin::getReportTime, DateUtil.format(newBulletin.getReportTime(), DateUtil.PATTERN_MONTH) + "-01")
                    .eq(NewBulletin::getOrgId, newBulletin.getOrgId())
                    .ne(NewBulletin::getStatus, 3));
            if (CollectionUtil.isNotEmpty(list)){
                ids = list.stream().map(NewBulletin::getId).collect(Collectors.toList());
            }
        }

        if (ids.size() == 0){
            ids.add(newBulletin.getId());
        }
        for (String id : ids) {
            formWorkflowService.deleteProcessInstance(id);
        }
        removeByIds(ids);
        bulletinSummaryRelationService.deleteByBaseId(ids);
        objResult = new R(CommonCode.SUCCESS);
        return objResult;
    }

    @Override
    public ListResult<NewBulletinVO> treeList(Query query) {
        List<SearchEntity> entityList = query.getSearch();
        if (query.getAscs()==null&&query.getDescs()==null){
            query.setDescs("report_time");
        }
        QueryWrapper<NewBulletin> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new NewBulletin()), entityList
        );
        String orgId = TokenUtil.getTokenOrgId();
        queryWrapper.lambda().eq(NewBulletin::getOrgId, orgId);

        try {
            PageData org = orgzationDao.findbyid(orgId);
            if ("3".equals(org.getString("type"))){
                List<PageData> parentList = new ArrayList<>();
                orgzationService.getParentList(org.getString("parentId"), parentList);
                int summaryCode = parentList.size();
                queryWrapper.lambda().eq(NewBulletin::getSummaryCode, summaryCode - 1);
            }

            getWrapper(queryWrapper, orgId);
        }catch (Exception e){
            LOGGER.error(ExceptionUtils.getStackTrace(e));
        }

        IPage<NewBulletin> pages = page(Condition.getPage(query), queryWrapper);
        ListResult<NewBulletinVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(newBulletinWrapper.entityToVO(pages.getRecords()));
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }

    @Override
    public ListResult<NewBulletinVO> childTree(NewBulletin newBulletin) {
        List<PageData> orgList = orgzationService.getSubordinate().getList();
        if (CollectionUtil.isEmpty(orgList)) {
            return new ListResult<>(CustomCode.builder().message("企业树初始化失败").code(1999).success(false).build());
        }
        List<NewBulletinVO> list = new ArrayList<>();
        try {
            List<String> orgIds = orgzationService.getSubordinateIds();
            List<NewBulletin> allBulletins = list(new LambdaQueryWrapper<NewBulletin>().in(NewBulletin::getOrgId, orgIds)
                    .eq(NewBulletin::getReportTime, DateUtil.format(newBulletin.getReportTime(), DateUtil.PATTERN_MONTH) + "-01"));
            list = getListTree(allBulletins, orgList, newBulletin.getReportTime()).get(0).getChildren();
        }catch (Exception e){
            log.error(ExceptionUtils.getFullStackTrace(e));
        }

        ListResult<NewBulletinVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(list);
        listResult.setTotal(list.size());
        return listResult;
    }

    public List<NewBulletinVO> getListTree(List<NewBulletin> allBulletins, List<PageData> orgList, Date reportTime) throws Exception {
        List<NewBulletinVO> tree = new ArrayList<>();

//       Map<String, NewBulletin> map = allBulletins.stream().collect(Collectors.toMap(bulletin ->
//                bulletin.getTableTypeCode() + "-" + bulletin.getOrgId() + "-" + bulletin.getSummaryCode(), bulletin -> bulletin));
        for (PageData org : orgList) {
            List<PageData> orgChildren = (List<PageData>) org.get("children");
            List<PageData> parentList = new ArrayList<>();
            String type = org.getString("type");
            int isVirtualNode = "3".equals(type) ? 2 : 1;
            switch (org.getString("typeCode")) {
                case "0":
                    NewBulletin bulletin = findOne("6", org.getString("id"),null, allBulletins);
                    NewBulletinVO bulletinVO = getInitVo("6", org.getString("name"), isVirtualNode);

                    if (bulletin != null) {
                        bulletinVO.setOrgId(bulletin.getOrgId());
                        bulletinVO.setId(bulletin.getId());
                        bulletinVO.setReportTime(reportTime);
                        bulletinVO.setStatus(bulletin.getStatus());
                    }

                    List<NewBulletinVO> childList = new ArrayList<>();

                    NewBulletin differenceBulletin = findOne("1", org.getString("id"),null, allBulletins);
                    NewBulletinVO differenceBulletinVO = getInitVo("1", org.getString("name"), isVirtualNode);
                    if (differenceBulletin != null) {
                        differenceBulletinVO.setOrgId(differenceBulletin.getOrgId());
                        differenceBulletinVO.setId(differenceBulletin.getId());
                        differenceBulletinVO.setReportTime(reportTime);
                        differenceBulletinVO.setStatus(differenceBulletin.getStatus());
                    }
                    childList.add(differenceBulletinVO);

                    NewBulletin singleBulletin = findOne("0", org.getString("id"),null, allBulletins);
                    NewBulletinVO singleBulletinVO = getInitVo("0", org.getString("name"), isVirtualNode);
                    if (singleBulletin != null) {
                        singleBulletinVO.setOrgId(singleBulletin.getOrgId());
                        singleBulletinVO.setId(singleBulletin.getId());
                        singleBulletinVO.setReportTime(reportTime);
                        singleBulletinVO.setStatus(singleBulletin.getStatus());
                    }

                    childList.add(singleBulletinVO);
                    childList.addAll(getListTree(allBulletins, orgChildren, reportTime));
                    bulletinVO.setChildren(childList);

                    if (isVirtualNode == 2){
                        System.out.println(1);
                    }
                    if (bulletinVO.getIsVirtualNode()  != isVirtualNode) {
                        System.out.println(1);
                    }
                    tree.add(bulletinVO);
                    break;
                case "1":
                    NewBulletin singleBulletin1 = findOne("0", org.getString("id"),null, allBulletins);
                    NewBulletinVO singleBulletinVO1 = getInitVo("0", org.getString("name"), isVirtualNode);
                    if (singleBulletin1 != null) {
                        singleBulletinVO1.setOrgId(singleBulletin1.getOrgId());
                        singleBulletinVO1.setId(singleBulletin1.getId());
                        singleBulletinVO1.setReportTime(reportTime);
                        singleBulletinVO1.setStatus(singleBulletin1.getStatus());
                    }

                    tree.add(singleBulletinVO1);
                    break;
                case "2":
                    NewBulletin singleBulletin2 = findOne("0", org.getString("id"),null, allBulletins);
                    NewBulletinVO singleBulletinVO2 = getInitVo("0", org.getString("name"), isVirtualNode);
                    if (singleBulletin2 != null) {
                        singleBulletinVO2.setOrgId(singleBulletin2.getOrgId());
                        singleBulletinVO2.setId(singleBulletin2.getId());
                        singleBulletinVO2.setReportTime(reportTime);
                        singleBulletinVO2.setStatus(singleBulletin2.getStatus());
                    }

                    tree.add(singleBulletinVO2);
                    break;
                case "3":
                    orgzationService.getParentList(org.getString("parentId"), parentList);
                    int summaryCode = parentList.size();
                    PageData pd = new PageData();
                    pd.put("id", org.getString("id"));
                    pd.put("typeCode", 2);
                    List<PageData> typeOrgs = orgzationDao.findorgbyidandtype(pd);
                    List<PageData> delOrgs = new ArrayList<>();
                    for (PageData orgType : typeOrgs) {
                        for (PageData child : orgChildren) {
                            if (child.getString("id").equals(orgType.getString("id"))) {
                                delOrgs.add(child);
                            }
                        }
                    }
                    orgChildren.removeAll(delOrgs);

                    NewBulletin bulletin3 = findOne("6", org.getString("id"),(summaryCode - 1) + "", allBulletins);
                    NewBulletinVO bulletinVO3 = getInitVo("6", org.getString("name"), isVirtualNode);

                    if (bulletin3 != null) {
                        bulletinVO3.setOrgId(bulletin3.getOrgId());
                        bulletinVO3.setId(bulletin3.getId());
                        bulletinVO3.setReportTime(reportTime);
                        bulletinVO3.setStatus(bulletin3.getStatus());
                    }


                    List<NewBulletinVO> childList3 = new ArrayList<>();
                    //遍历当前单位的下属子企业
                    List<NewBulletin> list = findList(reportTime, null, org.getString("id"), summaryCode + "");
                    if (CollectionUtil.isNotEmpty(list)) {
                        for (NewBulletin child : list) {
                            NewBulletinVO newBulletinVO4 = getInitVo(child.getTableTypeCode(), org.getString("name"), isVirtualNode);
                            newBulletinVO4.setReportTime(reportTime);
                            newBulletinVO4.setStatus(child.getStatus());
                            newBulletinVO4.setOrgId(child.getOrgId());
                            newBulletinVO4.setId(child.getId());
                            if ("6".equals(child.getTableTypeCode())) {
                                List<NewBulletinVO> summarySmallList = new ArrayList<>();
                                NewBulletin differenceSmall = findOne("1", org.getString("id"),(summaryCode + 1) + "", allBulletins);
                                NewBulletinVO differenceSmallVO = getInitVo("1", org.getString("name"), isVirtualNode);
                                if (differenceSmall != null){
                                    differenceSmallVO.setOrgId(differenceSmall.getOrgId());
                                    differenceSmallVO.setId(differenceSmall.getId());
                                    differenceSmallVO.setReportTime(reportTime);
                                    differenceSmallVO.setStatus(differenceSmall.getStatus());
                                    differenceSmallVO.setIsSmallSummary(1);
                                }
                                summarySmallList.add(differenceSmallVO);

                                NewBulletin singleSmall = findOne("0", org.getString("id"),(summaryCode + 1) + "", allBulletins);
                                NewBulletinVO singleSmallVO = getInitVo("0", org.getString("name"), isVirtualNode);
                                if (singleSmall != null){
                                    singleSmallVO.setOrgId(singleSmall.getOrgId());
                                    singleSmallVO.setId(singleSmall.getId());
                                    singleSmallVO.setReportTime(reportTime);
                                    singleSmallVO.setStatus(singleSmall.getStatus());
                                }
                                summarySmallList.add(singleSmallVO);

                                for (PageData branch : typeOrgs) {
                                    NewBulletin branchBulletin = findOne("0", branch.getString("id"),(summaryCode + 1) + "", allBulletins);
                                    NewBulletinVO branchVO = getInitVo("0", branch.getString("name"), isVirtualNode);
                                    if (branchBulletin != null){
                                        branchVO.setOrgId(branchBulletin.getOrgId());
                                        branchVO.setId(branchBulletin.getId());
                                        branchVO.setReportTime(reportTime);
                                        branchVO.setStatus(branchBulletin.getStatus());
                                    }
                                    summarySmallList.add(branchVO);
                                }

                                newBulletinVO4.setChildren(summarySmallList);
                                newBulletinVO4.setIsSmallSummary(1);
                            }

                            childList3.add(newBulletinVO4);
                        }
                    } else {
                        NewBulletinVO newBulletinVO4 = getInitVo("6", org.getString("name"), isVirtualNode);
                        childList3.add(newBulletinVO4);
                    }
                    childList3.addAll(getListTree(allBulletins, orgChildren, reportTime));
                    bulletinVO3.setChildren(childList3);
                    tree.add(bulletinVO3);
                    break;
                default:
                    break;
            }
        }
//        }
        return tree;
    }

    private NewBulletin findOne(String tableTypeCode, String orgId, String summaryCode, List<NewBulletin> allBulletin){
      for (NewBulletin newBulletin : allBulletin){
          if (tableTypeCode.equals(newBulletin.getTableTypeCode()) && orgId.equals(newBulletin.getOrgId())){
              if (StringUtil.isBlank(summaryCode)){
                  return newBulletin;
              }else {
                  if (summaryCode.equals(newBulletin.getSummaryCode())){
                      return newBulletin;
                  }
              }
          }
      }
      return null;
    }

    private List<NewBulletin> findList(Date reportTime, String tableTypeCode, String orgId, String summaryCode){
        QueryWrapper<NewBulletin> queryWrapper = new QueryWrapper<>();
        if (reportTime != null){
            queryWrapper.lambda().eq(NewBulletin::getReportTime, DateUtil.format(reportTime, DateUtil.PATTERN_DATE));
        }
        if (StringUtil.isNotBlank(tableTypeCode)){
            queryWrapper.lambda().eq(NewBulletin::getTableTypeCode, tableTypeCode);
        }
        if (StringUtil.isNotBlank(orgId)) {
            queryWrapper.lambda().eq(NewBulletin::getOrgId, orgId);
        }
        if (StringUtil.isNotBlank(summaryCode)){
            queryWrapper.lambda().eq(NewBulletin::getSummaryCode, summaryCode);
        }
        queryWrapper.lambda().orderByDesc(NewBulletin::getTableTypeCode);
        return list(queryWrapper);
    }

    private NewBulletinVO getInitVo(String tableTypeCode, String orgName, int isVirtualNode){
        NewBulletinVO bulletinVO = new NewBulletinVO();
        bulletinVO.setOrgName(orgName);
        bulletinVO.setTableTypeCode(tableTypeCode);
        bulletinVO.setStatus(String.valueOf(FormStatusConstant.NOFILLING));
        bulletinVO.setFormType(FormTypeConstant.FR_BULLETIN + "");
        bulletinVO.setIsVirtualNode(isVirtualNode);
        return bulletinVO;
    }

    @Override
    public R submit(NewBulletin newBulletin) {
        NewBulletin oldBulletin = getById(newBulletin.getId());
        oldBulletin.setBulletinValues(bulletinValueService.list(new LambdaQueryWrapper<BulletinValue>()
                .eq(BulletinValue::getBulletinId, newBulletin.getId())));
        updateById(newBulletin);
        bulletinValueService.updateBatchById(newBulletin.getBulletinValues());

        List<String> childIds = newBulletin.getChildIds();
        if (CollectionUtil.isNotEmpty(childIds)){
            bulletinSummaryRelationService.submit(newBulletin.getId(), childIds);
        }

        List<NewBulletin> list = new ArrayList<>();
        list.add(oldBulletin);
        list.add(newBulletin);
        applicationContext.publishEvent(new NewBulletinEvent(list));
        return new R(CommonCode.SUCCESS);
    }

    @Override
    public ListResult<NewBulletinVO> childList(NewBulletin newBulletin) {
        String orgId = newBulletin.getOrgId();
        ListResult<NewBulletinVO> listResult;
        try {
            List<PageData> children = orgzationDao.findchildbyid(orgId);
            if (CollectionUtil.isEmpty(children)){
                throw new MyRuntimeException(new ObjResult("获取下级单位失败！"));
            }

            String reportTime = DateUtil.format(newBulletin.getReportTime(), DateUtil.PATTERN_MONTH) + "-01";
            List<NewBulletinVO> bulletinVOS = baseMapper.summaryChildList(reportTime,
                    children.stream().map(p -> p.getString("id")).collect(Collectors.toList()));
            if (CollectionUtil.isNotEmpty(bulletinVOS)){
                PageData org = orgzationDao.findbyid(orgId);
                List<PageData> parentList = new ArrayList<>();
                orgzationService.getParentList(org.getString("parentId"), parentList);
                int summaryCode = parentList.size();

                int findSummaryCode = Integer.valueOf(newBulletin.getSummaryCode()) + 1;

                bulletinVOS = bulletinVOS.stream().filter(vo ->
                        !(orgId.equals(vo.getOrgId())
                                && findSummaryCode != Integer.valueOf(vo.getSummaryCode()))).collect(Collectors.toList());
                bulletinVOS.forEach(vo -> {
                    if (orgId.equals(vo.getOrgId())
                            && summaryCode == Integer.valueOf(vo.getSummaryCode()) && "6".equals(vo.getTableTypeCode())) {
                        vo.setIsSmallSummary(1);
                    }
                    if (orgId.equals(vo.getOrgId()) && summaryCode != Integer.valueOf(vo.getSummaryCode())
                            && "1".equals(vo.getTableTypeCode())){
                        vo.setIsSmallSummary(1);
                    }

                });
            }

            listResult = new ListResult<>(CommonCode.SUCCESS);
            listResult.setList(bulletinVOS);
            listResult.setTotal(bulletinVOS.size());
            return listResult;
        }catch (Exception e){
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            listResult = new ListResult<>(CommonCode.ERROR);
        }
        return listResult;
    }

    @Override
    public ListResult<BulletinValue> childSummary(NewBulletin newBulletin) {
        if (CollectionUtil.isEmpty(newBulletin.getChildIds())){
            return new ListResult<>(CommonCode.SUCCESS);
        }
        List<BulletinValue> oldValues = bulletinValueService.list(new LambdaQueryWrapper<BulletinValue>()
                .eq(BulletinValue::getBulletinId, newBulletin.getId()).orderByAsc(BulletinValue::getSortCode));

        List<BulletinValue> childValues = bulletinValueService.list(new LambdaQueryWrapper<BulletinValue>()
                .in(BulletinValue::getBulletinId, newBulletin.getChildIds()).orderByAsc(BulletinValue::getSortCode));
        for (BulletinValue bulletinValue : oldValues){
            bulletinValue.setLastYearMonthAmount(new BigDecimal(0));
            bulletinValue.setMonthAmount(new BigDecimal(0));
            bulletinValue.setYearAmount(new BigDecimal(0));
            for (BulletinValue childValue : childValues){
                if (childValue.getTypeCode().equals(bulletinValue.getTypeCode())){
                    bulletinValue.setLastYearMonthAmount(BigDecimalUtil.add(bulletinValue.getLastYearMonthAmount(),
                            childValue.getLastYearMonthAmount()));
                    bulletinValue.setMonthAmount(BigDecimalUtil.add(bulletinValue.getMonthAmount(),
                            childValue.getMonthAmount()));
                    bulletinValue.setYearAmount(BigDecimalUtil.add(bulletinValue.getYearAmount(),
                            childValue.getYearAmount()));
                }
            }
        }
        ListResult<BulletinValue> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(oldValues);
        listResult.setTotal(oldValues.size());

        return listResult;
    }

    @Override
    public ListResult<BulletinSummaryDetailVO> getSummaryDetail(BulletinValueVO bulletinValueVO) {
        ListResult<BulletinSummaryDetailVO> listResult = new ListResult<>(CommonCode.SUCCESS);

        List<BulletinSummaryDetailVO> list = baseMapper.getSummaryDetail(StringUtil.humpToUnderline(bulletinValueVO.getAmountName()),
                bulletinValueVO.getTypeCode(), bulletinValueVO.getBulletinId());
        listResult.setList(list);
        listResult.setTotal(list.size());
        return listResult;
    }

    @Override
    public R<NewBulletin> uploadFile(MultipartFile multipartFile, String reportTime) {
        R objResult;
        try {
            byte[] bytes = IOUtils.toByteArray(multipartFile.getInputStream());

            InputStream inputStream = new ByteArrayInputStream(bytes);
            List<Object> readList = new ArrayList<>();
            EasyExcel.read(inputStream).build()
                    .read(EasyExcel.readSheet(0).headRowNumber(1).head(NewBulletinExcelBean.class)
                            .registerReadListener(new PageReadListener<>(list -> readList.addAll(list))).build());
            ImportExcelUtil.filterEmpty(readList);
            List<BulletinValue> valueList = getInitByYear(reportTime.split(StringPool.DASH)[0], null);
            NewBulletin newBulletin = new NewBulletin();
            setValue(newBulletin, valueList, multipartFile);
            newBulletin.setBulletinValues(valueList);
            objResult = new R(CommonCode.SUCCESS);
            objResult.setPageData(newBulletin);
        }catch (Exception e){
            log.error(ExceptionUtils.getFullStackTrace(e));
            objResult = new R(CommonCode.ERROR);
        }

        return objResult;
    }

    private void setValue(NewBulletin newBulletin, List<BulletinValue> valueList, MultipartFile multipartFile){
        try {
            byte[] bytes = IOUtils.toByteArray(multipartFile.getInputStream());
            InputStream inputStream = new ByteArrayInputStream(bytes);
            List<Object> readList = new ArrayList<>();
            EasyExcel.read(inputStream).build()
                    .read(EasyExcel.readSheet(0).headRowNumber(1).head(NewBulletinExcelBean.class)
                            .registerReadListener(new PageReadListener<>(list -> readList.addAll(list))).build());
            ImportExcelUtil.filterEmpty(readList);
            for (Object object : readList){
                NewBulletinExcelBean excelBean = (NewBulletinExcelBean)object;
                String typeName = StringUtil.isNotBlank(excelBean.getTypeName()) ? StringUtil.cleanChars(excelBean.getTypeName()) : "";
                if (typeName.matches(NUMBER_DOT_PATTERN)){
                    typeName =  typeName.substring(typeName.indexOf(StringPool.DOT));
                }
                for (BulletinValue initValue : valueList){
                    String initTypeName = StringUtil.cleanChars(initValue.getTypeName());
                    if (initTypeName.matches(NUMBER_DOT_PATTERN)){
                        initTypeName =  initTypeName.substring(initTypeName.indexOf(StringPool.DOT));
                    }
                    if (StringUtil.isNotBlank(typeName) && typeName.equals(initTypeName)){
                        initValue.setId(null);
                        initValue.setYearAmount(BigDecimalUtil.replaceCommaToBigDecimal(excelBean.getYearAmount()));
                        initValue.setMonthAmount(BigDecimalUtil.replaceCommaToBigDecimal(excelBean.getMonthAmount()));
                        initValue.setLastYearMonthAmount(BigDecimalUtil.replaceCommaToBigDecimal(excelBean.getLastYearMonthAmount()));
                        break;
                    }
                }
                if (StringUtil.isNotBlank(excelBean.getTypeName()) &&
                        excelBean.getTypeName().contains("填表人：")){
                    newBulletin.setApplicant(excelBean.getTypeName().replace("填表人：",""));
                }
                if (StringUtil.isNotBlank(excelBean.getIndex()) &&
                        excelBean.getIndex().contains("联系电话：")){
                    newBulletin.setPhone(excelBean.getIndex().replace("联系电话：",""));
                }
                if (StringUtil.isNotBlank(excelBean.getMonthAmount()) &&
                        excelBean.getMonthAmount().contains("联系电话：")){
                    newBulletin.setPhone(excelBean.getMonthAmount().replace("联系电话：",""));
                }
            }
        }catch (Exception e){
            log.error(ExceptionUtils.getFullStackTrace(e));
            throw new RuntimeException(e);
        }
    }

    @Override
    public void exportExcel(NewBulletinVO newBulletinVO, HttpServletResponse response, OutputStream os) {
        try {
            String fileName = newBulletinVO.getOrgName() + StringPool.UNDERSCORE + newBulletinVO.getReportTime();
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "UTF-8") + ".xls");
            response.setContentType("application/msexcel");//定义输出类型
        }catch (Exception e){
            log.error(ExceptionUtils.getFullStackTrace(e));
        }

        InputStream inputStream = this.getClass().getResourceAsStream("/exceldemo/快报导出模板.xlsx");
        ExcelWriter excelWriter = EasyExcel.write(os).withTemplate(inputStream).build();
        WriteSheet writeSheet = EasyExcel.writerSheet(0).build();
        List<NewBulletinExcelBean> list = new ArrayList<>();
       for (int i = 0; i < newBulletinVO.getBulletinValues().size(); i++){
           BulletinValue value = newBulletinVO.getBulletinValues().get(i);
           NewBulletinExcelBean excelBean = NewBulletinExcelBean.builder().index(String.valueOf(i+1)).typeName(value.getTypeName())
                   .lastYearMonthAmount(BigDecimalUtil.toPlanString(value.getLastYearMonthAmount()))
                   .monthAmount(BigDecimalUtil.toPlanString(value.getMonthAmount()))
                   .yearAmount(BigDecimalUtil.toPlanString(value.getYearAmount())).build();
           if (value.getDisabled()){
               excelBean.setMonthAmount("────");
           }
           list.add(excelBean);
       }
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(list, fillConfig, writeSheet);
        Map<String, Object> map = new HashMap<>(16);
        map.put("applicant", newBulletinVO.getApplicant());
        map.put("phone", newBulletinVO.getPhone());
        excelWriter.fill(map, writeSheet);
        excelWriter.finish();

    }

    @Override
    public ListResult<NewBulletinVO> reportTree(NewBulletin newBulletin) {
        List<PageData> orgList = orgzationService.getSubordinate().getList();
        if (CollectionUtil.isEmpty(orgList)) {
            return new ListResult<>(CustomCode.builder().message("企业树初始化失败").code(1999).success(false).build());
        }
        List<NewBulletinVO> list = new ArrayList<>();
        try {
            List<String> orgIds = orgzationService.getSubordinateIds();
            List<NewBulletin> allBulletins = list(new LambdaQueryWrapper<NewBulletin>().in(NewBulletin::getOrgId, orgIds)
                    .eq(NewBulletin::getReportTime, DateUtil.format(newBulletin.getReportTime(), DateUtil.PATTERN_MONTH) + "-01"));
            list = getListTree(allBulletins, orgList, newBulletin.getReportTime());
        }catch (Exception e){
            log.error(ExceptionUtils.getFullStackTrace(e));
        }

        ListResult<NewBulletinVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(list);
        listResult.setTotal(list.size());
        return listResult;
    }

    @Override
    public List<NewBulletinVO> getSingleListByYear(String year, String orgId) {
        return baseMapper.getSingleListByYear(year, orgId);
    }

    @Override
    public List<NewBulletinVO> getGroupListByYear(String year, String orgId) {
        return baseMapper.getGroupListByYear(year, orgId);
    }

    @Override
    public NewBulletinVO getSingleOneByParam(NewBulletinVO newBulletinVO) {
        return baseMapper.getSingleOneByParam(newBulletinVO);
    }

    @Override
    public NewBulletinVO getGroupOneByParam(NewBulletinVO newBulletinVO) {
        return baseMapper.getGroupOneByParam(newBulletinVO);
    }

    @Override
    public List<Integer> findFillMonths(List<String> orgIds, String orgId, String year, String tableTypeCode) {
        LambdaQueryWrapper<NewBulletin> queryWrapper = new LambdaQueryWrapper<NewBulletin>()
                .eq(NewBulletin::getTableTypeCode, tableTypeCode).apply("DATE_FORMAT(report_time,'%Y')={0}", year);
        if (CollectionUtil.isNotEmpty(orgIds)){
            queryWrapper.in(NewBulletin::getOrgId, orgIds);
        }else {
            queryWrapper.eq(NewBulletin::getOrgId, orgId);
        }
        List<NewBulletin> list = list(queryWrapper);
        if (CollectionUtil.isEmpty(list)){
            return new ArrayList<>();
        }
        return list.stream().map(bulletin -> Integer.valueOf(DateUtil.format(bulletin.getReportTime(), DateUtil.PATTERN_ONLY_MONTH))).collect(Collectors.toList());
    }

    @Override
    public String getMaxReportTimeByOrgId(String orgId) {
        List<NewBulletin> newBulletinList = list(Wrappers.<NewBulletin>lambdaQuery()
                .eq(NewBulletin::getStatus, FormStatusConstant.FINISH)
                .eq(NewBulletin::getOrgId, orgId)
                .orderByDesc(NewBulletin::getReportTime));
        if (CollectionUtil.isEmpty(newBulletinList)){
            return DateUtil.format(DateUtil.now(), DateUtil.PATTERN_MONTH);
        }
        return DateUtil.format(newBulletinList.get(0).getReportTime(), DateUtil.PATTERN_MONTH);
    }

    @Override
    public String getMaxReportTimeByOrgIds(List<String> orgIds) {
        List<NewBulletin> newBulletinList = list(Wrappers.<NewBulletin>lambdaQuery()
                .eq(NewBulletin::getStatus, FormStatusConstant.FINISH)
                .in(NewBulletin::getOrgId, orgIds)
                .orderByDesc(NewBulletin::getReportTime));
        if (CollectionUtil.isEmpty(newBulletinList)){
            return DateUtil.format(DateUtil.now(), DateUtil.PATTERN_MONTH);
        }
        return DateUtil.format(newBulletinList.get(0).getReportTime(), DateUtil.PATTERN_MONTH);
    }

    @Override
    public String getMaxReportTimeByOrgIdsAndType(List<String> orgIds, int type) {
        List<NewBulletin> newBulletinList = list(Wrappers.<NewBulletin>lambdaQuery()
                .eq(NewBulletin::getStatus, FormStatusConstant.FINISH)
                .in(NewBulletin::getOrgId, orgIds)
                .eq(NewBulletin::getTableTypeCode, type)
                .orderByDesc(NewBulletin::getReportTime));
        if (CollectionUtil.isEmpty(newBulletinList)){
            return DateUtil.format(DateUtil.now(), DateUtil.PATTERN_MONTH);
        }
        return DateUtil.format(newBulletinList.get(0).getReportTime(), DateUtil.PATTERN_MONTH);
    }

    @Override
    public List<NewBulletin> findFinishByYear(int year) {
        List<NewBulletin> newBulletinList = list(Wrappers.<NewBulletin>lambdaQuery()
                .likeRight(NewBulletin::getReportTime, year)
                .ne(NewBulletin::getTableTypeCode, DIFFERENCE_TABLE_TYPE)
                .eq(NewBulletin::getStatus, FormStatusConstant.FINISH));
        if (CollectionUtil.isEmpty(newBulletinList)){
            return new ArrayList<>();
        }
        List<BulletinValue> bulletinValues = bulletinValueService.list(Wrappers.<BulletinValue>lambdaQuery()
                .in(BulletinValue::getBulletinId, newBulletinList.stream().map(NewBulletin::getId).collect(Collectors.toList())));
        Map<String, List<BulletinValue>> valueMap = bulletinValues.stream().collect(Collectors.groupingBy(BulletinValue::getBulletinId));
        for (NewBulletin newBulletin : newBulletinList){
            List<BulletinValue> values = valueMap.get(newBulletin.getId());
            if (CollectionUtil.isNotEmpty(values)){
                newBulletin.setBulletinValues(values);
            }
        }
        return newBulletinList;
    }

    @Override
    public List<NewBulletin> findFinishByReportTime(String reportTime) {
        List<NewBulletin> newBulletinList = list(Wrappers.<NewBulletin>lambdaQuery()
                .likeRight(NewBulletin::getReportTime, reportTime)
                .ne(NewBulletin::getTableTypeCode, DIFFERENCE_TABLE_TYPE)
                .eq(NewBulletin::getStatus, FormStatusConstant.FINISH));
        if (CollectionUtil.isEmpty(newBulletinList)){
            return new ArrayList<>();
        }
        List<BulletinValue> bulletinValues = bulletinValueService.list(Wrappers.<BulletinValue>lambdaQuery()
                .in(BulletinValue::getBulletinId, newBulletinList.stream().map(NewBulletin::getId).collect(Collectors.toList())));
        Map<String, List<BulletinValue>> valueMap = bulletinValues.stream().collect(Collectors.groupingBy(BulletinValue::getBulletinId));
        for (NewBulletin newBulletin : newBulletinList){
            List<BulletinValue> values = valueMap.get(newBulletin.getId());
            if (CollectionUtil.isNotEmpty(values)){
                newBulletin.setBulletinValues(values);
            }
        }
        return newBulletinList;
    }

    @Override
    public String ythExcelUpload(YthExcelInfoVO ythExcelInfoVO, MultipartFile multipartFile) {
        if (multipartFile == null){
            return JSON.toJSONString(YthResult.builder().failReason("文件为空!"));
        }
        Org org = orgService.getByDataSourceId(YthConstant.DATA_NINGBO, ythExcelInfoVO.getOrgId());
        if (org == null){
            return JSON.toJSONString(YthResult.builder().failReason(StringUtil.format("orgId = {} ,该单位不存在!", ythExcelInfoVO.getOrgId())));
        }
        int summaryCode = orgService.getSummaryCode(org);
        if (ythExcelInfoVO.getValueType() == EXCEL_MERGE){
            summaryCode = summaryCode - 1;
        }
        if ("3".equals(org.getTypeCode())){
            if (ythExcelInfoVO.getValueType() == EXCEL_SINGLE || ythExcelInfoVO.getValueType() == EXCEL_SINGLE){
                summaryCode = summaryCode + 1;
            }
        }

        String tableTypeCode = YthExcelUtils.valueTypeToTableType(ythExcelInfoVO.getValueType());
        NewBulletin oldBulletin = getOne(Wrappers.<NewBulletin>lambdaQuery()
                .eq(NewBulletin::getOrgId, org.getId())
                .likeRight(NewBulletin::getReportTime, ythExcelInfoVO.getReportTime())
                .eq(NewBulletin::getSummaryCode, summaryCode)
                .eq(NewBulletin::getTableTypeCode, tableTypeCode));
        if (oldBulletin != null && NOT_UPDATE_STATUS.contains(oldBulletin.getStatus())){
            return JSON.toJSONString(YthResult.builder()
                    .failReason(StringUtil.format("orgId = {} ,valueType = {}, reportTime = {},该单据已上报!",
                            ythExcelInfoVO.getOrgId(), ythExcelInfoVO.getValueType(), ythExcelInfoVO.getReportTime())));
        }

        List<BulletinValue> valueList;
        if (oldBulletin == null){
            oldBulletin = new NewBulletin();
            oldBulletin.setReportTime(DateUtil.parse(ythExcelInfoVO.getReportTime() +"-01", DateUtil.PATTERN_DATE));
            oldBulletin.setOrgId(org.getId());
            oldBulletin.setDataSource(YthConstant.DATA_NINGBO);
            oldBulletin.setStatus(FINISH + "");
            oldBulletin.setFormType(String.valueOf(FR_BULLETIN));
            oldBulletin.setSummaryCode(summaryCode + "");
            oldBulletin.setDataSourceId(ythExcelInfoVO.getFormId());
            oldBulletin.setTableTypeCode(tableTypeCode);
            save(oldBulletin);
            valueList = getInitByYear(ythExcelInfoVO.getReportTime().split(StringPool.DASH)[0], oldBulletin.getId());
        }else {
            valueList = bulletinValueService.list(Wrappers.<BulletinValue>lambdaQuery().eq(BulletinValue::getBulletinId, oldBulletin.getId()));
        }
        setValue(oldBulletin, valueList, multipartFile);
        updateById(oldBulletin);
        bulletinValueService.saveOrUpdateBatch(valueList);
        return JSON.toJSONString(YthResult.builder().successIds(Stream.of(ythExcelInfoVO.getFormId()).collect(Collectors.toList())));
    }


    private QueryWrapper<NewBulletin> getWrapper(QueryWrapper<NewBulletin> queryWrapper, String orgId) throws Exception{
        PageData org = orgzationDao.findbyid(orgId);
        switch (org.getString("typeCode")){
            case "0":
                queryWrapper.lambda().eq(NewBulletin::getTableTypeCode, "6");
                break;
            case "1":
                queryWrapper.lambda().eq(NewBulletin::getTableTypeCode, "0");
                break;
            case "2":
                queryWrapper.lambda().eq(NewBulletin::getTableTypeCode, "0");
                break;
            case "3":
                List<PageData> parentList = new ArrayList<>();
                queryWrapper.lambda().eq(NewBulletin::getTableTypeCode, "6");
                orgzationService.getParentList(org.getString("parentId"), parentList);
                int summaryCode = parentList.size();
                queryWrapper.lambda().eq(NewBulletin::getSummaryCode, summaryCode - 1);
                break;
            default:
                break;
        }
        return queryWrapper;
    }

    private void saveAndChild(String year, String orgId, String tableTypeCode, String reportTime, String summaryCode){
        String bulletinId = UuidUtil.get32UUID();
        NewBulletin newBulletin = NewBulletin.builder().orgId(orgId).formType("" + FormTypeConstant.FR_BULLETIN)
                .reportTime(DateUtil.parse(reportTime, DateUtil.PATTERN_DATE)).tableTypeCode(tableTypeCode).status(FormStatusConstant.UNREVIEWED + "")
                .summaryCode(summaryCode).id(bulletinId).build();
        save(newBulletin);
        HashMap<String, Object> processVariable = new HashMap<>();
        formWorkflowService.startProcessAndSimulate(newBulletin.getId(), newBulletin.getFormType(), processVariable);
        List<BulletinValue> values = getInitByYear(year, bulletinId);
        bulletinValueService.saveBatch(values);
    }


}
